package com.thehun.mickeymall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class MickeyMallFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                log.info("Feign远程调用之前先进行拦截处理...");
                // 拿到老请求的数据，底层也是threadLocal做的
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes == null) {
                    log.info("订单服务远程调用的拦截器出现空指针，请求属性为空，位置为：com.thehun.mickeymall.order.config.MickeyMallFeignConfig");
                    return;
                }
                HttpServletRequest request = requestAttributes.getRequest();
                // 同步请求头
                requestTemplate.header("Cookie", request.getHeader("Cookie"));
            }
        };
    }
}
